package com.xuzz.study.io.mynetty;

import lombok.Data;

import java.nio.channels.Channel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Date 2023/4/5 20:16
 * @Created by xuzz3@asiainfo-sec.com
 */
@Data
public class ThreadSelectorGroup {
    ThreadSelector[] threads;
    ServerBootStrap bootStrap;

    AtomicInteger index = new AtomicInteger(0);

    public ThreadSelectorGroup(int num) {
        num = num<1 ? 1 : num;
        this.threads = new ThreadSelector[num];

        ExecutorService bossExecutor = Executors.newFixedThreadPool(num, this.getThreadFactory());
        for(int i=0;i<num;i++){
            ThreadSelector threadSelector = new ThreadSelector(this);
            this.threads[i] = threadSelector;
            bossExecutor.execute(threadSelector);
        }
    }

    public ThreadFactory getThreadFactory() {
        return new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"thread_pool_selector");
            }
        };
    }

    /**
     * 获取下一个可用的线程
     * @param channel
     * @return
     */
    public ThreadSelector next(Channel channel) {
        return this.threads[this.index.getAndIncrement() % this.threads.length];
    }
}
